package com.mzba.easy.weibo.ui;

import java.util.ArrayList;
import java.util.List;

import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import com.actionbarsherlock.app.SherlockFragment;
import com.mzba.easy.weibo.MainActivity;
import com.mzba.easy.weibo.R;
import com.mzba.easy.weibo.db.MentionsTimelineTable;
import com.mzba.easy.weibo.db.StatusTimelineEntry;
import com.mzba.easy.weibo.db.StatusTimelineGson;
import com.mzba.easy.weibo.db.StatusTimelineTable;
import com.mzba.easy.weibo.db.UserTimelineTable;
import com.mzba.easy.weibo.util.AppContext;
import com.mzba.easy.weibo.util.BasicUIEvent;
import com.mzba.easy.weibo.util.UICore;
import com.mzba.easy.weibo.util.WeiboManager;
import com.mzba.easy.weibo.widget.CustomListView;

/**
 * 
 * @author 06peng
 *
 */
public class HomeFragment extends SherlockFragment implements BasicUIEvent, Callback {
	
	private CustomListView listView;
	private LinearLayout localView;
	private Handler handler;
	private WeiboManager weiboManager;
	private List<StatusTimelineEntry> timelineEntries;
	private StatusTimeLineAdapter adapter;
	private int count = 20;
	private int page = 1;
	private String since_id = "0";
	
	private final int get_timeline = 1;
	private final int refresh_timeline = 2;
	private final int get_more_data = 3;
	
	private boolean isLoading;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		handler = new Handler(this);
		weiboManager = new WeiboManager(getActivity());
		UICore.eventTask(this, (MainActivity) getActivity(), get_timeline, null);
	}
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_layout, null);
		if (localView != null) {
			localView.removeAllViews();
		}
		localView = (LinearLayout) view.findViewById(R.id.pager);
		if (listView == null) {
			listView = (CustomListView) inflater.inflate(R.layout.listview_layout, null);
		}
		listView.setSelector(R.drawable.list_bg_selector);
		listView.setonRefreshListener(new CustomListView.OnRefreshListener() {
			
			@Override
			public void onRefresh() {
				refreshTimelineFragment();
			}
		});
		listView.setonLoadListener(new CustomListView.OnLoadListener() {
			
			@Override
			public void onLoad() {
				UICore.eventTask(HomeFragment.this, (MainActivity) getActivity(), get_more_data, null);
			}
		});
		return view;
	}
	
	@Override
	public void execute(int mes, Object obj) {
		try {
			switch (mes) {
			case get_timeline:
				getTimelines();
				handler.sendEmptyMessage(get_timeline);
				break;
			case get_more_data:
				getMoreTimeline();
				handler.sendEmptyMessage(get_more_data);
				break;
			case refresh_timeline:
				refreshTimeline();
				handler.sendEmptyMessage(get_timeline);
				break;
			default:
				break;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void getTimelineFragment() {
		if (timelineEntries != null) {
			timelineEntries.clear();
			if (adapter != null) {
				adapter.notifyDataSetChanged();
			}
		}
		UICore.eventTask(this, (MainActivity) getActivity(), get_timeline, null);
	}
	
	public void refreshTimelineFragment() {
		UICore.eventTask(this, (MainActivity) getActivity(), refresh_timeline, null);
	}
	
	private void getTimelines() {
		try {
			if (timelineEntries != null) {
				timelineEntries.clear();
			}
			page = 1;
			since_id = "0";
			isLoading = false;
			StatusTimelineGson timeline = null;
			switch (((MainActivity) getActivity()).groupItem) {
			case 0: //首页
				StatusTimelineTable timelineTable = new StatusTimelineTable();
				timelineEntries = timelineTable.getAllStatus();
				if (timelineEntries == null || timelineEntries.isEmpty()) {
					timeline = weiboManager.getFriendsTimeLine(count, page, since_id);
					timelineEntries = timeline.getStatuses();
					if (timelineEntries != null && timelineEntries.size() > 0) {
						since_id = timelineEntries.get(0).getId();
					}
					timelineTable.save(timelineEntries);
				}
				break;
			case 1: //@我的微博
				MentionsTimelineTable mentionTable = new MentionsTimelineTable();
				timelineEntries = mentionTable.getAllStatus();
				if (timelineEntries == null || timelineEntries.isEmpty()) {
					timeline = weiboManager.getMentionsimeLine(count, page, since_id);
					timelineEntries = timeline.getStatuses();
					if (timelineEntries != null && timelineEntries.size() > 0) {
						since_id = timelineEntries.get(0).getId();
					}
					mentionTable.save(timelineEntries);
				}
				break;
			case 2: //我的微博
				UserTimelineTable userTimelineTable = new UserTimelineTable();
				timelineEntries = userTimelineTable.getAllStatus();
				if (timelineEntries == null || timelineEntries.isEmpty()) {
					timeline = weiboManager.getUserTimeline(AppContext.getInstance().getUid(), count, page, since_id);
					timelineEntries = timeline.getStatuses();
					if (timelineEntries != null && timelineEntries.size() > 0) {
						since_id = timelineEntries.get(0).getId();
					}
					userTimelineTable.save(timelineEntries);
				}
				break;
//			case 3: //我的收藏
//				FavoriteTimelineTable favoriteTable = new FavoriteTimelineTable();
//				timelineEntries = favoriteTable.getAllStatus();
//				if (timelineEntries == null || timelineEntries.isEmpty()) {
//					timelineEntries = weiboManager.getFavorites(count, page);
//					favoriteTable.save(timelineEntries);
//				}
//				break;
			default:
				break;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void refreshTimeline() {
		try {
			page = 1;
			isLoading = false;
			StatusTimelineGson timeline = null;
			switch (((MainActivity) getActivity()).groupItem) {
			case 0: //首页
				timeline = weiboManager.getFriendsTimeLine(count, page, since_id);
				StatusTimelineTable timelineTable = new StatusTimelineTable();
				List<StatusTimelineEntry> newTimelineEntries = timeline.getStatuses();
				if (newTimelineEntries != null && !newTimelineEntries.isEmpty()) {
					List<StatusTimelineEntry> temp = new ArrayList<StatusTimelineEntry>(timelineEntries);
					timelineEntries.clear();
					timelineEntries.addAll(newTimelineEntries);
					timelineEntries.addAll(temp);
					timelineTable.save(timelineEntries);
					since_id = timelineEntries.get(0).getId();
				}
				break;
			case 1: //@我的微博
				MentionsTimelineTable mentionTable = new MentionsTimelineTable();
				timeline = weiboManager.getMentionsimeLine(count, page, since_id);
				List<StatusTimelineEntry> newMenstionTimelineEntries = timeline.getStatuses();
				if (newMenstionTimelineEntries != null && !newMenstionTimelineEntries.isEmpty()) {
					List<StatusTimelineEntry> temp = new ArrayList<StatusTimelineEntry>(timelineEntries);
					timelineEntries.clear();
					timelineEntries.addAll(newMenstionTimelineEntries);
					timelineEntries.addAll(temp);
					mentionTable.save(timelineEntries);
					since_id = timelineEntries.get(0).getId();
				}
				break;
			case 2: //我的微博
				UserTimelineTable userTimelineTable = new UserTimelineTable();
				timeline = weiboManager.getUserTimeline(AppContext.getInstance().getUid(), count, page, since_id);
				List<StatusTimelineEntry> newUsereTimelineEntries = timeline.getStatuses();
				if (newUsereTimelineEntries != null && !newUsereTimelineEntries.isEmpty()) {
					List<StatusTimelineEntry> temp = new ArrayList<StatusTimelineEntry>(timelineEntries);
					timelineEntries.clear();
					timelineEntries.addAll(newUsereTimelineEntries);
					timelineEntries.addAll(temp);
					userTimelineTable.save(timelineEntries);
					since_id = timelineEntries.get(0).getId();
				}
				break;
//			case 3: //我的收藏
//				FavoriteTimelineTable favoriteTable = new FavoriteTimelineTable();
//				List<StatusTimelineEntry> newFavoriteTimelineEntries = weiboManager.getFavorites(count, page);
//				if (newFavoriteTimelineEntries != null && !newFavoriteTimelineEntries.isEmpty()) {
//					List<StatusTimelineEntry> temp = new ArrayList<StatusTimelineEntry>(timelineEntries);
//					timelineEntries.clear();
//					timelineEntries.addAll(newFavoriteTimelineEntries);
//					timelineEntries.addAll(temp);
//					favoriteTable.save(timelineEntries);
//				}
//				break;
			default:
				break;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void getMoreTimeline() {
		try {
			page ++;
			StatusTimelineGson timeline = null;
			List<StatusTimelineEntry> moredatas = null;
			switch (((MainActivity) getActivity()).groupItem) {
			case 0: //首页
				timeline = weiboManager.getFriendsTimeLine(count, page, "0");
				moredatas = timeline.getStatuses();
				if (moredatas != null && !moredatas.isEmpty()) {
					timelineEntries.addAll(moredatas);
				}
				break;
			case 1: //@我的微博
				timeline = weiboManager.getMentionsimeLine(count, page, "0");
				moredatas = timeline.getStatuses();
				if (moredatas != null && !moredatas.isEmpty()) {
					timelineEntries.addAll(moredatas);
				}
				break;
			case 2: //我的微博
				timeline = weiboManager.getUserTimeline(AppContext.getInstance().getUid(), count, page, "0");
				moredatas = timeline.getStatuses();
				if (moredatas != null && !moredatas.isEmpty()) {
					timelineEntries.addAll(moredatas);
				}
				break;
//			case 3: //我的收藏
//				moredatas = weiboManager.getFavorites(count, page);
//				if (moredatas != null && !moredatas.isEmpty()) {
//					timelineEntries.addAll(moredatas);
//				}
//				break;
			default:
				break;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public boolean handleMessage(Message msg) {
		switch (msg.what) {
		case get_timeline:
			isLoading = true;
			if (timelineEntries != null && !timelineEntries.isEmpty()) {
				adapter = new StatusTimeLineAdapter(getActivity(), timelineEntries, listView);
				listView.setAdapter(adapter);
			}
			listView.onRefreshComplete();
			break;
		case get_more_data:
			if (adapter != null) {
				adapter.notifyDataSetChanged();
			}
			listView.setSelection(adapter.getCount() - 20);
			listView.onLoadComplete();
			break;
		default:
			break;
		}
		return false;
	}
	
	@Override
	public void onResume() {
		super.onResume();
		if (isLoading) {
			((MainActivity) getActivity()).loadFinish();
		} else {
			((MainActivity) getActivity()).loading();
		}
		localView.removeAllViews();
		localView.addView(listView);
	}
	
}
